<?php

namespace cmf\controller;

/**
 * hprose统一控制器
 * 
 * @author chenliming <chenliming@lacertafashion.com>
 * @since     2016-12-4
 * 
 */
class HprosebaseController extends HproseController {

    protected $crossDomain = true;
    protected $P3P = true;
    protected $get = true;
    protected $debug = true;

    function _initialize() {
        parent::_initialize();
    }

    public function test() {
//        return urldecode(json_encode(['a'=>'中国']));
//        return get_client_ip();
        return self::success(get_client_ip());
//        return self::success(['a' => 1]);
//        return self::success(78.56);
//        return self::success(true);
    }

    protected function error($message, $is_json = false) {
        $data = [];
        $data['alert'] = $message;
        return self::ajaxReturn($data, FALSE, $is_json == true ? 'JSON' : '');
    }

    public function success($content, $is_json = false) {
        return self::ajaxReturn($content, true, $is_json == true ? 'JSON' : '');
    }

    /**
     * 按不同方式返回数据到客户端
     * @access protected
     * @return void
     */
    protected function ajaxReturn($content, $state = 1, $type = '', $json_option = 0) {
        switch (strtoupper($type)) {
            case 'JSON' :
                $data = [];
                $data['result'] = $state == 1 ? true : false;
                $data['detail'] = $content;
                $data['msg'] = is_array($content) && isset($content['alert']) ? $content['alert'] : '';
                $data['code'] = intval($state);
                $data['detail'] = jsonUnicode2gbk($data['detail']);
                // 返回JSON数据格式到客户端 包含状态信息
//                $data['detail'] = jsonUnicode2gbk($data['detail']);
                return urldecode(json_encode($data, $json_option));
            default :
                if (is_string($content) || is_numeric($content) || is_null($content) || is_double($content)) {
                    return $content;
                }

                if (is_bool($content)) {
                    return ($content == FALSE) ? 0 : 1;
                }

                //转成json发
                return urldecode(json_encode($content));
        }
    }

}
